package com.zcn.io.web.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.zcn.io.common.exception.ServiceException;
import com.zcn.io.web.api.dto.DictDto;
import com.zcn.io.web.api.entity.SysRole;
import com.zcn.io.web.api.entity.User;
import com.zcn.io.web.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    public User getByAccountNo(String accountNo) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getAccountNo, accountNo);
        return userMapper.selectOne(queryWrapper);
    }

    public List<SysRole> getRolesByUserId(String userId) {
        return userMapper.getRolesByUserId(userId);
    }

    public List<User> list() {
        return this.userMapper.selectList(new LambdaQueryWrapper<>());
    }

    public void save(User user) {
        //判重
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getAccountNo, user.getAccountNo());
        if (this.userMapper.selectCount(queryWrapper) > 0) {
            throw new ServiceException("账号已存在!");
        }
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        user.setPassword(encoder.encode(user.getPassword()));
        this.userMapper.insert(user);
    }

    public List<DictDto> dict() {
        return this.userMapper.dict();
    }
}
